using System.Collections.Generic;

namespace NScriptEngine
{
    public class Engine
    {
        #region Public Interface
        ///////////////////////////////////////////////////////////////////////
        //// Public 
        ///////////////////////////////////////////////////////////////////////
        public Engine()
        {
            _scripts = new List<Script>();
            _references = new Dictionary<string, object>();
        }

        public void LoadScript(string file)
        {
            Script script = _ScriptFactory(file);
            if (null != script)
            {
                _scripts.Add(script);
            }
        }

        public void AddReference(string name, object objToRef)
        {
            _references.Add(name, objToRef);
            foreach (Script script in _scripts)
            {
                script.AddReference(name, objToRef);
            }
        }

        public void CastEvent(string eventName, object[] eventArgs)
        {
            foreach (Script script in _scripts)
            {
                script.CastEvent(eventName, eventArgs);
            }
        }

        #endregion

        #region Private Impl
        ///////////////////////////////////////////////////////////////////////
        //// Private
        ///////////////////////////////////////////////////////////////////////

        internal Script _ScriptFactory(string file)
        {
            string[] tokens = file.Split('.');
            if (tokens.Length < 2)
            {
                return null;
            }

            string fileExt = tokens[tokens.Length - 1].ToLower();
            if (PyScript.IsValidFileExtension(fileExt))
                return new PyScript(file, _references);
            
            if (VBScript.IsValidFileExtension(fileExt))
                return new VBScript(file, _references);
            
            if (CSharpScript.IsValidFileExtension(fileExt))
                return new CSharpScript(file, _references);

            return null;
        }

        internal List<Script> _scripts;
        internal Dictionary<string, object> _references;
        #endregion
    }

}
